/**
 *@描述：菜单管理
 *@作者：顾云飞
 *@创建时间：2023/1/17
 *@最后修改时间：2023/1/18
 */
import { SearchOutlined, PlusOutlined, SyncOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Card, Table, Space, Popconfirm, Button, message, Tag, Form, Input } from 'antd';
import { queryMenuList, DeleteMenuRequest } from '@/pages/Dashboard/System/Menu/service';
import { useRef, useState, useEffect } from 'react';
import { GetMenuListRequestParams, GetMenuListResponse } from './data';
import MenuFormModal from './MenuFormModal';
import type { ColumnsType } from 'antd/es/table';

const { Meta } = Card;
import _ from 'lodash';
interface MenuItem {
  id: string;
  name: string;
  status: string;
  roleCode: string;
  permission: string;
  isShow: string;
  type: string;
  sort: number;
  createTime: string;
  updateTime: string;
}

const MenuList = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const [expandedRowKeys, setExpadnRowKeys] = useState<string[]>([]);
  const [showMenuModal, setShowMenuModal] = useState<boolean>(false);
  const [menuFormValues, setMenuFormValues] = useState({});
  const [menuId, setMenuId] = useState(''); // 当前menuid 弹窗的父级菜单的id

  //组件初始化函数
  //todo: useEffect函数
  useEffect(() => {
    getMenuList({});
  }, []);
  const columns: ColumnsType<MenuItem> = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
      width: 160,
    },
    {
      title: '菜单类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (_, record) => (
        <Space>
          {record.type === 'CATALOG' && <Tag color="error">目录</Tag>}
          {record.type === 'BUTTON' && <Tag color="success">按钮</Tag>}
          {record.type === 'MENU' && <Tag color="warning">菜单</Tag>}
          {record.type === 'EXTLINK' && <Tag color="default">外链</Tag>}
        </Space>
      ),
    },
    {
      title: '权限标识',
      dataIndex: 'permission',
      key: 'permission',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'isShow',
      key: 'isShow',
      width: 80,
      render: (_, record) => (
        <Space>
          <Tag color={record.isShow === '1' ? 'success' : 'default'} key={record.status}>
            {record.isShow === '1' ? '显示' : '隐藏'}
          </Tag>
        </Space>
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 60,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 160,
    },
    {
      title: '操作',
      key: 'operation',
      width: 160,
      render: (_, record) => [
        record.type !== 'BUTTON' && record.type !== 'EXTLINK' && (
          <Button
            type="link"
            size="small"
            onClick={() => {
              setShowMenuModal(true);
              setMenuId(record.id);
            }}
          >
            新增
          </Button>
        ),
        <Button
          type="link"
          onClick={() => {
            setShowMenuModal(true);
            setMenuFormValues(record);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          title="确认删除吗？"
          okText="确定"
          cancelText="取消"
          onConfirm={() => delMenu(record.id)}
        >
          <Button
            // className={styles.removeBtn}
            size="small"
            type="link"
            danger
          >
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  //根据菜单ID，删除菜单，调用DeleteMenuRequest接口
  //todo: 删除菜单
  const delMenu = async (id?: string) => {
    setLoading(true);
    const res = await DeleteMenuRequest({
      id: id,
    });
    if (res.code == 200) {
      setLoading(false);
      getMenuList({});
      message.success('删除成功！');
    } else {
      setLoading(false);
      message.error('删除失败！');
    }
  };
  //添加菜单成功触发的函数
  //todo: onSuccess
  const onSuccess = async () => {
    getMenuList({});
  };
  const onCancel = () => {
    setShowMenuModal(false);
    setMenuFormValues({});
  };
  // 选择
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  // 递归查找children
  //  const formateList = (data:any) => {
  //    _.forEach(data, item => {
  //      if(item.children&&item.children.length > 0) {
  //       setExpadnRowKeys(expandedRowKeys =>[...expandedRowKeys, item.id])
  //       formateList(item.children)
  //      }
  //    })
  //  }
  //查询列表，可通过菜单名称查询
  const getMenuList = async ({ keyword }: { keyword?: string }) => {
    setLoading(true);
    const requestParams: GetMenuListRequestParams = {
      keyword: keyword,
    };
    // console.log(requestParams);
    const res = await queryMenuList(requestParams);
    if (res.code == 200) {
      setData(res.data);
      // formateList(res.data)
      // @ts-ignore
      // setTotal(res.data.total);
    }
    setLoading(false);
  };

  return (
    <div>
      <Card style={{ marginBottom: '20px' }}>
        <Form layout="inline">
          <Form.Item label="菜单名称">
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button type="default" icon={<SyncOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Card
        title={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setShowMenuModal(true);
                setMenuId('1');
              }}
            >
              新增
            </Button>
          </Space>
        }
      >
        {data.length && (
          <Table
            columns={columns}
            dataSource={data}
            rowSelection={{
              //  selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
              //  alwaysShowAlert:true,
              selectedRowKeys,
              onChange: onSelectChange,
            }}
            defaultExpandAllRows={true}
            loading={loading}
            //  actionRef={actionRef}
            //  cardBordered
            //   request ={ async (
            //   params: {},
            //  sort, filter) => {
            //     const res = await queryMenuList();
            //     setExplandData(res.data)
            //     return {
            //       data: res.data ? res.data: []
            //     }
            //  }}
            //  editable={{
            //    type: 'multiple',
            //  }}
            //  columnsState={{
            //    persistenceKey: 'pro-table-singe-demos',
            //    persistenceType: 'localStorage',
            //  }}
            rowKey="id"
            size="small"
            //  tableAlertOptionRender={() => {
            //   return (
            //     <Space size={16}>
            //       <Button type="primary" icon={<PlusOutlined />} onClick={() => setShowMenuModal(true)}>新增菜单</Button>
            //       <Popconfirm
            //       title="确认删除吗？"
            //       okText="确定"
            //       cancelText="取消"
            //       onConfirm={() => {
            //         delUser(selectedRowKeys.toString())
            //       }}
            //   >
            //       <Button
            //           // className={styles.removeBtn}
            //           type="link"
            //           danger
            //       >批量删除</Button>
            //   </Popconfirm>,
            //       {/* <a>导出数据</a> */}
            //     </Space>
            //   );
            // }}
            //  scroll={{ y: 300 }}
            pagination={false}
          />
        )}
      </Card>
      {(menuFormValues && Object.keys(menuFormValues).length) || showMenuModal ? (
        <MenuFormModal
          parentMenuId={menuId}
          menuFormValues={menuFormValues}
          onSuccess={onSuccess}
          show={showMenuModal}
          onCancel={onCancel}
        ></MenuFormModal>
      ) : null}
    </div>
  );
};
export default MenuList;
